package com.application.chat.handler;

import java.util.ArrayList;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import com.application.actor.manage.ActorManage;
import com.application.actor.pojo.Actor;
import com.application.chat.action.ChatAction;
import com.core.action.ActionConstants;
import com.core.utils.Constants;
import com.core.utils.GameUtils;
import com.core.utils.I18NUtils;
import com.core.utils.PushDataUtils;
import com.core.utils.StringFilter;
import com.core.utils.StringUtil;

public class PrivateChatHandler extends AbstractChatHandler {

	@Override
	public void handle(IoSession session, IoBuffer ioBuffer) {
		Actor a = ActorManage.getActorBySessionId(session.getId());
		if (a != null) {
			String dialog = StringUtil.getString(ioBuffer,
					Constants.DEFAULT_CHARSET);
			byte faceSize = ioBuffer.get();
			List<String> faces = new ArrayList<String>();
			if (faceSize > 0) {
				for (int i = 0; i < faceSize; i++) {
					String face = StringUtil.getString(ioBuffer,
							Constants.DEFAULT_CHARSET);
					faces.add(face);
				}
			}
			int uid = ioBuffer.getInt();
			Actor b = ActorManage.getOnlineActor(uid);
			if(b == null){
				this.sendError(session, I18NUtils.get("ACTOR_OFFLINE"));
				return;
			}
			boolean filterResult = StringFilter.filterString(dialog,
					Constants.COMMONFILTER);
			if (!filterResult) {
				this.sendError(session, I18NUtils.get("DIALOG_ILLEGAL"));
				return;
			}
			IoBuffer sendBuffer = IoBuffer.allocate(128);
			sendBuffer.setAutoExpand(true);
			sendBuffer.putInt(ActionConstants.S2C_ACTION_CHAT);
			sendBuffer.put(ChatAction.CHAT_TYPE_PRIVATE);
			StringUtil.putString(sendBuffer, dialog, Constants.DEFAULT_CHARSET);
			sendBuffer.putInt(a.getId());
			StringUtil.putString(sendBuffer, a.getNickname(),
					Constants.DEFAULT_CHARSET);
			sendBuffer.put(faceSize);
			if (faceSize > 0) {
				for (int i = 0; i < faceSize; i++) {
					StringUtil.putString(sendBuffer, faces.get(i),
							Constants.DEFAULT_CHARSET);
				}
			}

			sendBuffer.flip();
			b.getSession().write(sendBuffer);

		} else {
			this.sendError(session, I18NUtils.get("CHAT_SEND_FAILD"));
		}
	}
}
